package view.swing;


import game.BoardState;
import game.GameDice;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SwingView {
	
	private JFrame frame;
	private JButton[][] map;
	private Class<SwingView> myClass = SwingView.class;
	private SwingListener sl = new SwingListener();
	
	public SwingView() {
		this.frame   = new JFrame("The Conquest Game");
		this.map     = new JButton[8][9];
		for (int i=0; i<8; i++) {
			for (int j=0; j<9; j++) {
				map[i][j] = new JButton();
			}
		}
	}
	
	public void layout(BoardState bs) {
		Container con 	 = frame.getContentPane();
		JPanel gameBoard = new JPanel();
		frame.setVisible(true);
		frame.setSize(675, 600);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		gameBoard.setLayout(new GridLayout(8, 9));
		
		for (int i=0; i<8; i++) {
			for (int j=0; j<9; j++) {
				gameBoard.add(map[i][j]);
				if ((i+j)%2 == 0)
					map[i][j].setBackground(Color.WHITE);
				else if ((i+j)%2 == 1)
					map[i][j].setBackground(Color.BLACK);
			}
		}
		con.add(gameBoard, BorderLayout.CENTER);
		for (int i=0; i<8; i++) {
			for (int j=0; j<9; j++) {
				GameDice[][] board = bs.getBoard();
				String dir = board[i][j].getDiceColour().getShortName() + "_" + board[i][j].getDiceType().getShortName() + ".png";
				if (!dir.equals("n_n.png")) {
					map[i][j].setIcon(new ImageIcon(myClass.getResource(dir)));
					map[i][j].setName(board[i][j].getDiceColour().getShortName() + "_" + board[i][j].getDiceType().getShortName() + j + i);
					map[i][j].addActionListener(sl);
				}

			}
		}
	}
	
	public class SwingListener implements ActionListener {

		public void actionPerformed(ActionEvent event) {
			JButton b = (JButton) event.getSource();
			System.out.print(b.getName());
		}
	}


}
